package com.steel.yfmall.cloud.assistant.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.steel.yfmall.cloud.assistant.api.stock.CqOrderService;
import com.steel.yfmall.cloud.assistant.bean.param.ZgOrderParamBean;
import com.steel.yfmall.cloud.assistant.bean.result.ContractInfoBean;
import com.steel.yfmall.cloud.assistant.common.mapper.SteelSystemRegionAreaInfoBeanMapper;
import com.steel.yfmall.cloud.assistant.goods.mapper.FrameworkContractGoodsInfoMapper;
import com.steel.yfmall.cloud.assistant.goods.mapper.FrameworkContractInfoMapper;
import com.steel.yfmall.cloud.assistant.goods.mapper.ProductSellerGoodsMapper;
import com.steel.yfmall.cloud.assistant.oms.mapper.MasterOrderAddressInfoMapper;
import com.steel.yfmall.cloud.assistant.oms.mapper.MasterOrderGoodsMapper;
import com.steel.yfmall.cloud.assistant.oms.mapper.MasterOrderInfoExtendMapper;
import com.steel.yfmall.cloud.assistant.oms.mapper.MasterOrderInfoMapper;
import com.steel.yfmall.cloud.assistant.po.common.SteelSystemRegionAreaInfoBean;
import com.steel.yfmall.cloud.assistant.po.common.SteelSystemRegionAreaInfoBeanExample;
import com.steel.yfmall.cloud.assistant.po.goods.*;
import com.steel.yfmall.cloud.assistant.po.oms.*;
import com.steel.yfmall.cloud.assistant.po.user.UserBase;
import com.steel.yfmall.cloud.assistant.po.user.UserBaseExample;
import com.steel.yfmall.cloud.assistant.po.view.OutCallApiLogBean;
import com.steel.yfmall.cloud.assistant.user.mapper.UserBaseMapper;
import com.steel.yfmall.cloud.assistant.utils.HttpSendUtil;
import com.steel.yfmall.cloud.assistant.utils.kd.CosmicLoginUtil;
import com.steel.yfmall.cloud.components.mq.bean.RequestSendMQBean;
import com.steel.yfmall.cloud.components.mq.service.MqSendService;
import com.steel.yfmall.cloud.components.utils.base.APIMsgBean;
import com.steel.yfmall.cloud.components.utils.base.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: CqOrderServiceImpl
 * @author: liuzhijun
 * @date: 2021-04-08 13:13
 **/
@Service
@Slf4j
public class CqOrderServiceImpl implements CqOrderService {

    @Value("${ds_cosmic_orderdetail_url}")
    private String DS_COSMIC_ORDERDETAIL_URL;

    @Resource
    private MasterOrderInfoMapper masterOrderInfoMapper;
    @Resource
    private MasterOrderAddressInfoMapper masterOrderAddressInfoMapper;
    @Resource
    private MasterOrderInfoExtendMapper masterOrderInfoExtendMapper;
    @Resource
    private MasterOrderGoodsMapper masterOrderGoodsMapper;

    @Resource
    private FrameworkContractInfoMapper frameworkContractInfoMapper;

    @Resource
    private FrameworkContractGoodsInfoMapper frameworkContractGoodsInfoMapper;

    @Resource
    private MqSendService mqSendService;

    @Resource
    private ProductSellerGoodsMapper productSellerGoodsMapper;

    @Resource
    private SteelSystemRegionAreaInfoBeanMapper steelSystemRegionAreaInfoBeanMapper;

    @Resource
    private UserBaseMapper userBaseMapper;

    @Override
    public APIMsgBean<ContractInfoBean> createPushOrderToCq(ZgOrderParamBean zgOrderParamBean) {
        APIMsgBean<ContractInfoBean> resultOrderInfoAPIMsgBean = new APIMsgBean<>();
        resultOrderInfoAPIMsgBean.setSoaStateBean(ResponseCode.buildEnumErrorSOAStateBean());
        try {
            if (log.isDebugEnabled()) {
                log.info("OrderPushCangQiongListener  doOrderPushCangQiongSync  order_push_cq_listener: " + JSON.toJSONString(zgOrderParamBean));
            }
            if (zgOrderParamBean == null || StringUtils.isBlank(zgOrderParamBean.getMasterOrderSn())) {
                log.error("销售平台订单推送苍穹:参数为空！");
                return resultOrderInfoAPIMsgBean;
            }
            String strOrderNo = zgOrderParamBean.getMasterOrderSn();
            if (strOrderNo != null && strOrderNo.length() > 0) {
                MasterOrderInfo orderInfo = null;
                MasterOrderInfoExample example = new MasterOrderInfoExample();
                example.createCriteria().andMasterOrderSnEqualTo(strOrderNo);
                orderInfo = masterOrderInfoMapper.selectOneByExampleSelective(example);
                if (orderInfo != null) {
                    String strErr = "";

                    List<String> regionCode = new ArrayList<>();
                    MasterOrderAddressInfo addressInfo = null;
                    try {
                        MasterOrderAddressInfoExample exampleS = new MasterOrderAddressInfoExample();
                        exampleS.createCriteria().andMasterOrderSnEqualTo(strOrderNo);
                        addressInfo = masterOrderAddressInfoMapper.selectOneByExampleSelective(exampleS);
                        regionCode.add(addressInfo.getCity());
                        regionCode.add(addressInfo.getDistrict());
                    } catch (Exception exx) {
                        log.error("销售平台订单推送苍穹失败: " + JSON.toJSONString(zgOrderParamBean) + " 地址信息获取失败" + exx.getMessage());
                    }

                    MasterOrderInfoExtend addressInfoExtend = null;
                    try {
                        MasterOrderInfoExtendExample exampleS = new MasterOrderInfoExtendExample();
                        exampleS.createCriteria().andMasterOrderSnEqualTo(strOrderNo);
                        addressInfoExtend = masterOrderInfoExtendMapper.selectOneByExampleSelective(exampleS);
                    } catch (Exception exx) {
                        log.error("销售平台订单推送苍穹失败: " + JSON.toJSONString(zgOrderParamBean) + " 扩展信息获取失败" + exx.getMessage());
                    }

                    UserBase userBase = null;
                    try {
                        UserBaseExample userBaseExample = new UserBaseExample();
                        userBaseExample.or().andUserNameEqualTo(orderInfo.getUserName());
                        userBase = userBaseMapper.selectOneByExampleSelective(userBaseExample);
                    } catch (Exception e) {
                        log.error("销售平台订单推送苍穹失败: " + JSON.toJSONString(zgOrderParamBean) + " 用户信息获取失败" + e.getMessage());
                    }


                    //是否锁价，y是，n否
                    String isSuoJia = "N";
                    String settlementType = "";
                    //查询合同
                    FrameworkContractInfo frameworkContractInfo = new FrameworkContractInfo();
                    if (StringUtils.isNotBlank(orderInfo.getCustomerContractNum())) {
                        FrameworkContractInfoExample contractInfoExample = new FrameworkContractInfoExample();
                        contractInfoExample.createCriteria().andCommerceContractNoEqualTo(orderInfo.getCustomerContractNum());
                        frameworkContractInfo = frameworkContractInfoMapper.selectOneByExampleSelective(contractInfoExample);
                        if (frameworkContractInfo.getContractNewType().equals("S") || frameworkContractInfo.getContractNewType().equals("J")) {
                            isSuoJia = "Y";
                        }
                        settlementType = frameworkContractInfo.getSettletype();
                    }
                    //查询合同商品
                    Map<String, FrameworkContractGoodsInfo> spuMap = new HashMap<>();
                    FrameworkContractGoodsInfoExample goodsInfoExample = new FrameworkContractGoodsInfoExample();
                    goodsInfoExample.createCriteria().andCommerceContractNoEqualTo(orderInfo.getCustomerContractNum());
                    List<FrameworkContractGoodsInfo> frameworkContractGoodsInfos = frameworkContractGoodsInfoMapper.selectByExample(goodsInfoExample);
                    if (frameworkContractGoodsInfos != null && frameworkContractGoodsInfos.size() > 0) {
                        for (FrameworkContractGoodsInfo frameworkContractGoodsInfo : frameworkContractGoodsInfos) {
                            spuMap.put(frameworkContractGoodsInfo.getProductSysCode(), frameworkContractGoodsInfo);
                        }
                    }


                    List<String> spuList = new ArrayList<>();
                    MasterOrderGoodsExample goodsExample = new MasterOrderGoodsExample();
                    goodsExample.createCriteria().andMasterOrderSnEqualTo(strOrderNo);
                    List<MasterOrderGoods> goodsInfos = masterOrderGoodsMapper.selectByExample(goodsExample);
                    if (goodsInfos != null || goodsInfos.size() == 0) {
                        for (MasterOrderGoods goodsInfo : goodsInfos) {
                            spuList.add(goodsInfo.getGoodsSn());
                        }
                    }

                    Map<String, ProductSellerGoods> spubeanMap = new HashMap<>();
                    if (spuList != null && spuList.size() > 0) {
                        ProductSellerGoodsExample sellerGoodsExample = new ProductSellerGoodsExample();
                        sellerGoodsExample.createCriteria().andProductSysCodeIn(spuList);
                        List<ProductSellerGoods> productSellerGoods = productSellerGoodsMapper.selectByExample(sellerGoodsExample);
                        for (ProductSellerGoods productSellerGood : productSellerGoods) {
                            spubeanMap.put(productSellerGood.getProductSysCode(), productSellerGood);
                        }
                    }

                    //查询地址省市区信息
                    String city = "";
                    String district = "";
                    SteelSystemRegionAreaInfoBeanExample systemRegionAreaInfoBeanExample = new SteelSystemRegionAreaInfoBeanExample();
                    systemRegionAreaInfoBeanExample.createCriteria().andRegionIdIn(regionCode);
                    List<SteelSystemRegionAreaInfoBean> steelSystemRegionAreaInfoBeans = steelSystemRegionAreaInfoBeanMapper.selectByExample(systemRegionAreaInfoBeanExample);
                    if (steelSystemRegionAreaInfoBeans != null && steelSystemRegionAreaInfoBeans.size() > 0) {
                        for (SteelSystemRegionAreaInfoBean steelSystemRegionAreaInfoBean : steelSystemRegionAreaInfoBeans) {
                            if (steelSystemRegionAreaInfoBean.getRegionType() == 2) {
                                city = steelSystemRegionAreaInfoBean.getRegionId();
                            } else if (steelSystemRegionAreaInfoBean.getRegionType() == 3) {
                                district = steelSystemRegionAreaInfoBean.getRegionId();
                            }
                        }
                    }

                    MasterOrderGoods masterOrderGoods = goodsInfos.get(0);

                    JSONObject bill = new JSONObject();
                    JSONArray billentry = new JSONArray();
                    JSONArray recplanentry = new JSONArray();
//            yfgt_ecomordercod	 单据编号
                    bill.put("yfgt_ecomordercode", orderInfo.getMasterOrderSn());
//            bizdate	订单日期	Date
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                    bill.put("bizdate", dateFormat.format(orderInfo.getCreateTime()));
//            billstatus	单据状态	String
                    bill.put("billstatus", "A");
//            yfgt_procategorie	产品大类	String
                    bill.put("yfgt_procategorie", orderInfo.getProductTypeNo().substring(0, 1));
//            yfgt_salemonth	销售月份	date
                    bill.put("yfgt_salemonth", dateFormat.format(orderInfo.getCreateTime()));
//            yfgt_saletype	销售方式	String
                    bill.put("yfgt_saletype", "");
                    if (addressInfo != null) {
                        //  yfgt_destination	终到地点	String
                        bill.put("yfgt_destination", addressInfo.getLocaleCode());
                        //            yfgt_disarea	终到区域	String\
                        bill.put("yfgt_disarea", addressInfo.getFinishAreaCode());
                        //            yfgt_traffictype	运输方式	String
                        bill.put("yfgt_traffictype", addressInfo.getCartCode());
                    }
//            comment	备注	String
                    bill.put("comment", orderInfo.getPostscript());
//            yfgt_balancetype	结算方式	String
                    bill.put("yfgt_balancetype", settlementType);
//            yfgt_freightpayment	运费支付方式	String
                    bill.put("yfgt_freightpayment", orderInfo.getSettlementTicket());
//             yfgt_lockorder  是否锁价
                    bill.put("yfgt_lockorder", isSuoJia);
//              yfgt_weighttype 计重方式
                    bill.put("yfgt_weighttype", masterOrderGoods.getCountWgtMode());

                    //车牌号 ：yfgt_carnumber2
                    bill.put("yfgt_carnumber2", orderInfo.getSpecifyCarNumber());
                    //司机姓名：yfgt_driversname；
                    bill.put("yfgt_driversname", orderInfo.getSpecifyDriverName());
                    //司机电话：yfgt_driversphone
                    bill.put("yfgt_driversphone", orderInfo.getSpecifyDriverMobile());

//                    销售信息
//            payingcustomer	付款方	String
                    bill.put("payingcustomer", orderInfo.getCompanyCode());
//            customer	客户	String
                    bill.put("customer", orderInfo.getCompanyCode());
//            address	联系地址	String
                    bill.put("address", addressInfo.getAddress());
//            linkmanphone	联系人电话	String
                    bill.put("yfgt_linkmanphone", addressInfo.getMobile());
//            receiveaddress	收货地址	String
                    bill.put("receiveaddress", addressInfo.getAddress());
//            reccustomer	收货方	String
                    bill.put("reccustomer", orderInfo.getCompanyCode());
//            yfgt_end_user	最终用户	String
                    //子账户下单  传主账户信息字段：客户编码、付款方编码、收货方编码。 当子账号对应最终用户为空时，传主账号编码至最终用户字段，当子账号对应最终用户有值时，将最终用户传输至苍穹最终用户字段。
                    if (userBase != null && userBase.getManagerCode() == 2 && StringUtils.isNotBlank(userBase.getLastUserName())) {
                        bill.put("yfgt_end_user", userBase.getLastUserName());
                        //子账户用户名
                        bill.put("yfgt_child_account", userBase.getUserName());
                    } else {
                        bill.put("yfgt_end_user", orderInfo.getCompanyCode());
                    }
//            reclinkman	收货联系人	String
                    bill.put("yfgt_reclinkman", addressInfo.getConsignee());
//            settlecustomer	收票方	String
                    bill.put("settlecustomer", "");
//            dept	销售部门	String
                    bill.put("dept", "");
//            operator	销售员	String
                    bill.put("operator", "");
//            operatorgroup	销售组	String
                    bill.put("operatorgroup", "");
//            org	销售组织	String
                    String brandCode = "";
                    if (masterOrderGoods.getBrandCode().equals("YF")) {
                        brandCode = "YF00000000";
                    } else if (masterOrderGoods.getBrandCode().equals("LG")) {
                        brandCode = "L100000000";
                    }
                    bill.put("org", brandCode);
//                    财务信息
//            currency	本位币	String
                    bill.put("currency", "CNY");
//            paymode	付款方式	String
                    bill.put("paymode", "CASH");
                    //yfgt_paygoods 货款项
                    bill.put("yfgt_paygoods", orderInfo.getAccountNumber());
//            istax	含税	String
                    bill.put("istax", "true");
//            exchangerate	汇率	String
                    bill.put("exchangerate", "1");
//            exratetable	汇率表	String
                    bill.put("exratetable", "ERT-01");
//            exratedate	汇率日期	date
                    bill.put("exratedate", dateFormat.format(orderInfo.getCreateTime()));
//            totalallamount	价税合计	String
                    // bill.put("totalallamount", orderInfo.getTotalFee());
//            settlecurrency	结算币别	String
                    bill.put("settlecurrency", "CNY");
//            settletype	结算方式	String
                    bill.put("settletype", "");
//            totalamount	金额	BigDecimal
                    bill.put("totalamount", "");
//            receiptamount	累计收款金额	BigDecimal
                    bill.put("receiptamount", "");
//            prereceiptamount	累计预收款金额	BigDecimal
                    bill.put("prereceiptamount", "");
//            reccondition	收款条件	String
                    bill.put("reccondition", "");
//            totaltaxamount	税额	String
                    bill.put("totaltaxamount", "");
//              yfgt_carrier_type 承运方式
                    bill.put("yfgt_carrier_type", orderInfo.getTypeOfCarriage());
//            yfgt_pay_number  运费付款账户
                    bill.put("yfgt_pay_number", orderInfo.getConsignorCode());
//  ├         yfgt_destination_city 字符串 否 是 目的地城市
                    bill.put("yfgt_destination_city", district);
                    //详细地址
                    bill.put("yfgt_detailed_address", addressInfo.getAddress());
                    //定向物流公司名称
                    bill.put("yfgt_company_name", orderInfo.getShippingCompany());

                    //定向车辆
                    bill.put("yfgt_carnumber", orderInfo.getCarNumber());

                    //目的地县
                    bill.put("yfgt_goal_county", district);

                    //是否含税价，1是，0否；手动输入的运费单价为否，接口返回的运费单价为是
                    bill.put("yfgt_is_include_tax", orderInfo.getIsIncludedPrice());

                    //运费单价
                    bill.put("yfgt_freight_price", orderInfo.getShippingUnitPrice());


//            订单明细-物料明细

                    if (goodsInfos != null) {
                        for (MasterOrderGoods goodsInfo : goodsInfos) {
                            JSONObject entry = new JSONObject();
//            materialmasterid	物料	String
//                            entry.put("materialmasterid", "");
//            material	物料编码	String
//                            entry.put("material", "");
//            materialnamep	物料名称	String
//                            entry.put("materialnamep", "");
//            model	规格型号	String
//                            entry.put("model", "");
//            materialversion	物料版本	String
//                            entry.put("materialversion", "");
//            auxpty	辅助属性	String
//                            entry.put("auxpty", "");
//            yfgt_roductform	产品形态	String
                            ProductSellerGoods productSellerGoods = spubeanMap.get(goodsInfo.getGoodsSn());

                            entry.put("yfgt_roductform", productSellerGoods.getProductTypeNo());
//            yfgt_id_card	 牌号
                            entry.put("yfgt_id_card", productSellerGoods.getProductTradeno());
//            yfgt_reservedate	预定交期	String
                            entry.put("yfgt_reservedate", dateFormat.format(orderInfo.getCreateTime()));
//            yfgt_deliverydate	发货日期	String
                            entry.put("yfgt_deliverydate", dateFormat.format(orderInfo.getCreateTime()));
//            yfgt_qualitytype	品质分类	String
                            entry.put("yfgt_qualitytype", productSellerGoods.getProductGrade());
//            yfgt_size	尺寸信息	String
                            entry.put("yfgt_size", productSellerGoods.getSizeInformation());
//            yfgt_iswater	是否穿水	String
                            entry.put("yfgt_iswater", productSellerGoods.getCraft());
                            //yfgt_technology  工艺
                            if (productSellerGoods.getCraft() == 0) {
                                entry.put("yfgt_technology","");
                            } else {
                                entry.put("yfgt_technology", productSellerGoods.getCraft());
                            }

                            //yfgt_apnno(用途码
                            entry.put("yfgt_apnno", productSellerGoods.getApnNo());

                            //,yfgt_psrno (产品规范标准代码)
                            entry.put("yfgt_psrno", productSellerGoods.getPsrNo());

//            yfgt_factory	厂区	String
                            entry.put("yfgt_factory", goodsInfo.getBrandCode());
//            yfgt_basedatafield1	库区	String
                            entry.put("yfgt_stockplace", goodsInfo.getDepotCode());
//            yfgt_type	大小件	String
                            entry.put("yfgt_type", productSellerGoods.getSizePieces());
//            yfgt_change_level	是否降级	String
                            entry.put("yfgt_change_level", productSellerGoods.getIsDowngrade());
//            yfgt_colcr	颜色名称	String
                            entry.put("yfgt_colcr", productSellerGoods.getColor());
//            yfgt_diameter	直径（mm）	String
                            entry.put("yfgt_diameter", productSellerGoods.getProductThick());
//            yfgt_length	长度（mm）	String
                            entry.put("yfgt_length", productSellerGoods.getProductLen());
//            yfgt_packages	件数	String
                            entry.put("yfgt_packages", goodsInfo.getGoodsQty());
//            unit	计量单位	String
                            entry.put("unit", "t");
//            qty	订货量	String
                            entry.put("qty", goodsInfo.getSendWeight());
//            baseunit	基本单位	String
                            entry.put("baseunit", "");
//            baseqty	基本数量	String
                            entry.put("baseqty", "");
//            auxunit	辅助单位	String
                            entry.put("auxunit", "");
//            auxqty	辅助数量	String
                            entry.put("auxqty", "");
//            price	单价	String
                            entry.put("price", "");
//            priceandtax	含税单价	String
                            entry.put("priceandtax", goodsInfo.getGoodsPrice());
                            //价税合计
                            // entry.put("amountandtax", goodsInfo.getTransactionPrice());
//            taxrate	税率(%)	String
                            entry.put("taxrate", "13");
//                    srcbillnumber 源合同号
                            entry.put("srcbillnumber", orderInfo.getCustomerContractNum());
// srcbillentryseq 字符串 源合同行号
                            if (spuMap != null && spuMap.size() > 0 && spuMap.get(goodsInfo.getGoodsSn()) != null) {
                                FrameworkContractGoodsInfo frameworkContractGoodsInfo = spuMap.get(goodsInfo.getGoodsSn());
                                entry.put("srcbillentryseq", frameworkContractGoodsInfo.getCqProductSysCode());
                            }
                            billentry.add(entry);
                        }
                    } else {
                        strErr += "商品明细获取失败";
                    }
                    bill.put("billentry", billentry);
                    bill.put("recplanentry", recplanentry);
//                    bill.put("yfgt_ecomordercode", "XSDD-210331-000003");
                    String apptoken = CosmicLoginUtil.GetAPPToken();
                    String accessToken = CosmicLoginUtil.getAccessToken(apptoken);
                    String url = DS_COSMIC_ORDERDETAIL_URL + "?access_token=" + accessToken;
                    JSONObject semdData = new JSONObject();
                    semdData.put("bill", bill);
                    log.info("订单推送苍穹参数" + JSON.toJSONString(bill));
                    String result = HttpSendUtil.sendPost(url, JSONObject.toJSONString(semdData));
                    try {
                        JSONObject re = JSONObject.parseObject(result);
                        Object data = re.get("data");
                        JSONObject jsonObject = JSONObject.parseObject(data.toString());

                        OutCallApiLogBean outCallApiLogBean = new OutCallApiLogBean();
                        outCallApiLogBean.setApiUrl(url);
                        outCallApiLogBean.setParaText(JSON.toJSONString(bill));
                        outCallApiLogBean.setInterfaceMethod(url);
                        outCallApiLogBean.setInterfaceMethodName("订单推送苍穹");
                        outCallApiLogBean.setResultText(result);
                        RequestSendMQBean requestSendMQBean = new RequestSendMQBean();
                        requestSendMQBean.setSendMqTitle("insert_out_call_api_log");

                        requestSendMQBean.setSendMqMessage(JSON.toJSONString(outCallApiLogBean));
                        mqSendService.sendCommonMQMessage(requestSendMQBean);

                        if (jsonObject.get("isSuccess").toString().equals("true")) {
                            resultOrderInfoAPIMsgBean.setSoaStateBean(ResponseCode.buildEnumSuccessSOAStateBean());
                            return resultOrderInfoAPIMsgBean;
                        }
                    } catch (Exception ex) {
                        log.error("销售平台订单推送苍穹失败: 返回结果转换json失败 结果为：[" + result + "] " + JSON.toJSONString(zgOrderParamBean), ex);
                    }

                } else {
                    log.error("销售平台订单推送苍穹失败: " + JSON.toJSONString(zgOrderParamBean) + " 订单不存在");
                }
            } else {
                log.error("销售平台订单推送苍穹失败: " + JSON.toJSONString(zgOrderParamBean) + " 订单号不能为空");
            }
        } catch (Exception e) {
            log.error("销售平台订单推送苍穹失败: " + JSON.toJSONString(zgOrderParamBean), e);
        }
        return resultOrderInfoAPIMsgBean;
    }
}
